<template>
  <div class="chat-container">
    <div class="chat-content">
      <!-- 头部 -->
      <div class="chat-header">
        <div class="header-title">
          <span class="ai-name">小租</span>
        </div>
        <el-button class="back-button" @click="$router.back()" icon="el-icon-back">返回(Esc)</el-button>
      </div>

      <!-- 消息列表 -->
      <div class="message-list" ref="messageList">
        <div
          v-for="msg in messages"
          :key="msg.id"
          class="message-item"
          :class="{ 'message-self': msg.role === 'user' }"
        >
          <!-- 头像 -->
          <div class="avatar">
            <div class="avatar-text" :class="{ 'ai-avatar': msg.role === 'assistant' }">
              {{ msg.role === 'user' ? username.charAt(0).toUpperCase() : '租' }}
            </div>
          </div>
          <!-- 气泡 + 时间 -->
          <div class="message-wrapper">
            <div class="message-content" v-html="msg.role === 'assistant' ? renderMarkdown(msg.content) : msg.content"></div>
            <div class="message-time">
              {{ formatTime(msg.timestamp) }}
            </div>
          </div>
        </div>
        
        <!-- 加载动画 -->
        <div v-if="sending" class="loading-wrapper">
          <el-loading></el-loading>
        </div>
      </div>

      <!-- 输入区 -->
      <div class="message-input">
        <div class="input-wrapper">
          <el-input
            v-model="newMessage"
            type="textarea"
            :rows="3"
            placeholder="请输入消息..."
            @keyup.enter.ctrl="sendMessage"
            :disabled="sending"
          />
          <el-button
            type="primary"
            @click="sendMessage"
            :loading="sending"
            class="send-button"
          >
          发送(Q)
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.chat-container {
  height: 100vh;
  padding: 20px;
  background-color: #f5f5f5;
}

.chat-content {
  max-width: 1000px;
  margin: 0 auto;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  height: calc(100vh - 40px);
}

.chat-header {
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
}

.ai-name {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}

.back-button {
  margin-left: auto;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
  width: 100%;
  justify-content: flex-start;
}

.message-self {
  flex-direction: row-reverse;
}

.avatar {
  width: 40px;
  height: 40px;
  margin: 0 10px;
}

.avatar-text {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}

.ai-avatar {
  background-color: #67C23A;
}

.message-wrapper {
  max-width: 70%;
}

.message-content {
  color: black;
  padding: 12px 16px;
  background: #e8f3ff;
  border-radius: 12px;
  word-break: break-word;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: relative;
  text-align: left;
}

.message-self .message-content {
  background: #409EFF;
  color: white;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  text-align: right;
}

.message-input {
  padding: 20px;
  border-top: 1px solid #eee;
}

.input-wrapper {
  display: flex;
  gap: 10px;
  align-items: flex-start;
}

.el-input {
  flex: 1;
}

.send-button {
  height: 80px;
  width: 80px;
}

.loading-wrapper {
  display: flex;
  justify-content: center;
  padding: 20px;
}
</style>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import dayjs from 'dayjs'
import { marked } from 'marked'

const router = useRouter()

const messages = ref([])
const newMessage = ref('')
const sending = ref(false)
const messageList = ref(null)
const username = ref(localStorage.getItem('username') || '用户')

const renderMarkdown = (text) => {
  return marked.parse(text)
}

async function sendMessage() {
  if (!newMessage.value.trim() || sending.value) return
  sending.value = true
  
  const messageContent = newMessage.value.trim()
  newMessage.value = ''
  
  // 添加用户消息
  messages.value.push({
    id: Date.now(),
    role: 'user',
    content: messageContent,
    timestamp: new Date()
  })
  
  scrollToBottom()
  
  try {
    const response = await axios.post('/ai/chat', {
      content: messageContent
    })
    
    console.log('AI响应数据:', response.data) // 添加调试日志
    
    if (response.data.status === 200) {
      // 添加AI回复
      messages.value.push({
        id: Date.now() + 1,
        role: 'assistant',
        content: response.data.data.content,
        timestamp: new Date()
      })
    } else {
      ElMessage.error(response.data.msg || 'AI回复失败')
    }
} catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败：' + (error.response?.data?.msg || error.message))
}
  
  scrollToBottom()
  
  // 最终设置发送状态为false
  sending.value = false
  scrollToBottom()
}

const formatTime = (time) => {
  return dayjs(time).format('HH:mm')
}

const scrollToBottom = () => {
  nextTick(() => {
    if (messageList.value) {
      messageList.value.scrollTop = messageList.value.scrollHeight
    }
  })
}

// 全局键盘事件处理函数
const handleKeydown = (e) => {
  // 处理Ctrl+Q快捷键
  if (e.ctrlKey && e.key === 'q') {
    e.preventDefault() // 阻止默认行为
    if (!sending.value) {
      sendMessage()
    }
  }
  
  // 处理Esc快捷键
  if (e.key === 'Escape') {
    e.preventDefault() // 阻止默认行为
    router.back()
  }
}

onMounted(() => {
  messages.value.push({
    id: Date.now(),
    role: 'assistant',
    content: '你好，我是小租。很高兴见到你，有什么可以帮忙的吗？',
    timestamp: new Date()
  })

  scrollToBottom()
  
  // 添加全局键盘事件监听
  window.addEventListener('keydown', handleKeydown)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  // 移除全局键盘事件监听
  window.removeEventListener('keydown', handleKeydown)
})
</script>